# -*- coding: utf-8 -*-
# created by Src - 一路好时光

# 2.11 练习题- ⽤户登录认证程序
# 要求⽤户输⼊帐号密码进⾏登陆
# ⽤户账号信息保存在⽂件内
# ⽤户密码输⼊错误三次后锁定⽤户，下次再登录，检测到是这个被锁定的⽤户，则依然不允许其它
# 登录，提示已被锁

#思路
#1.确定在文件里，存储的账号信息的结构
f=open('account.db','r')
#2.把账号数据读到内存，为了方便调用，可以改dict
account_dict={}
for line in f:
    # print(line)
    #strip()去除换行
    line=line.strip().split(",")
    account_dict[line[0]] = line
print(account_dict)
f.close()

#{'a': 'alex,abc123,0\n', 'j': 'jack,ssss3,0\n', 'r': 'rain,ab333s,0'}
#key只有开头  alex--->a，为什么呢？


#3.搞个loop，要求用户输入账号信息，去判断就可以了

while True:
    user = input("Username:").strip()
    if user not in account_dict:
        print("该用户未注册")
        continue
    elif account_dict[user][2]=="1":
        print("此账户已锁定，请联系管理员...")
        continue
    count = 0
    while count < 3:
        passwd = input("Password:").strip()
        #去账号dict里去判断password对不对
        if passwd == account_dict[user][1]:
            print(f"Welcome {user}...登录成功")
            exit("login success")
        else:
            print("Wrong Password...")
        count+=1
    #锁定账号
    if count == 3:
        print(f"输错了{count}次密码，需要锁定账号{user}...")
        #1.先改在内存中dict的账号信息，用户状态
        #2.把dict里的数据按原account.db数据格式，并且存回文件
        account_dict[user][2]="1"
        f2=open('account.db','w')
        for user,val in account_dict.items():
            line=",".join(val)+"\n"#把列表再转换成字符
            f2.write(line)
        f2.flush()
        f2.close()
        exit("bye...")


# {'alex': ['alex', 'abc123', '0'], 'jack': ['jack', 'ssss3', '0'], 'rain': ['rain', 'ab333s', '0']}
# Username:alex
# Password:abc123
# Welcome alex...登录成功
# Username:alex
# Password:222
# Wrong Password...
# Username:ddd
# 该用户未注册
# Username:alex
# Password:abc123
# Welcome alex...登录成功


# Username:alex
# 此账户已锁定，请联系管理员...
# Username:jack
# Password:ssss3
# Welcome jack...登录成功
# login success